<?php

declare(strict_types=1);

namespace App\Model;

use App\Constants\FemaleKeepPushCode;
use App\Helpers\AliyunUtil;
use App\Helpers\ConfigUtil;
use Hyperf\DbConnection\Db;
use Hyperf\DbConnection\Model\Model;

/**
 *  送礼物记录
 */
class GiftLog extends Model
{
    protected $table = 'gift_log';

    protected $fillable = [
        "user_id", "receive_user_id", "flag", "gift_id", "gift_coin", "order_id", "from", "exp_time", "gift_num"
    ];

    //待领取
    const STATUS_WAIT = 0;
    //已领取
    const STATUS_OK = 1;
    //过期
    const STATUS_EXP = 2;

    const STATUS = [
        self::STATUS_WAIT => '待领取',
        self::STATUS_OK => '已领取',
        self::STATUS_EXP => '已失效',
    ];

    //普通赠送
    const FROM_SEND = 0;
    //注册-以系统名义赠送
    const FROM_SYS_REG = 1;
    //上线-以系统名义赠送
    const FROM_SYS_ONLINE = 2;
    //视频通话中赠送
    const FROM_VIDEO_CALL = 3;
    //语音通话中赠送
    const FROM_VOICE_CALL = 4;
    //主页搭讪
    const FROM_SUPER_CHAT = 5;
    //主播给男用户的名义礼物
    const FROM_HOST_TO_USER = 6;
    //视频通话-男方回赠
    const FROM_VIDEO_CALL_BACK = 7;
    //视频通话-主播免费赠送
    const FROM_VIDEO_CALL_FREE = 8;

    //注册 -以系统名义赠送给女生
    const FROM_SYS_REGISTER_FEMALE = 9;

    function giftInfo()
    {
        return $this->belongsTo(Gift::class, 'gift_id', 'id');
    }

    /**
     * 礼物记录
     */
    static function addRecord(
        $userId = 0,
        $receiveUserId = 0,
        $giftId = 1,
        $giftCoin = 0,
        $needFetch = false,
        $sendFrom = self::FROM_SEND,
        $expTime = 0,
        $giftNum = 1
    ) {
        $info = [
            'user_id' => $userId,
            'receive_user_id' => $receiveUserId,
            'gift_id' => $giftId,
            'gift_coin' => $giftCoin,
            'from' => $sendFrom,
            'flag' => $needFetch ? self::STATUS_WAIT : self::STATUS_OK,
            'exp_time' => $expTime,
            'gift_num' => $giftNum
        ];
        return self::create($info);
    }

    /**
     * 赠送用户ID
     */
    static function checkSendUserIds($userId = 0, $sendFrom = 0, $offTime = 2 * 3600)
    {
        $where = [
            ['user_id', $userId],
        ];
        $sendFrom && $where[] = ['from', $sendFrom];
        $offTime && $where[] = ['created_at', '>', date('Y-m-d H:i:s', time() - $offTime)];
        $userIds = self::where($where)->pluck('receive_user_id')->toArray();
        return $userIds ? array_unique($userIds) : [];
    }

    /**
     * 添加系统礼物赠送记录
     */
    static function addSysGiftRecord(
        $userId = 0,
        $receiveUserId = 0,
        $from = self::FROM_SYS_ONLINE,
        $needFetch = true,
        $sysGift = [],
        $expTime = 180
    ) {
        !$sysGift && $sysGift = Gift::sysGift();
        $ret = self::addRecord(
            $userId,
            $receiveUserId,
            $sysGift['id'],
            $sysGift['coin'],
            $needFetch,
            $from,
            $expTime,
        );
        return $ret;
    }

    /**
     * 系统礼物赠送总数
     */
    static function getAllCount($type = 'today', $giftId = 0)
    {
        //默认系统礼物
        !$giftId && $giftId = Gift::sysGift('id');
        $where = [
            ['gift_id', $giftId]
        ];
        switch ($type) {
            case 'today':
                $where[] = ['created_at', '>', date('Y-m-d')];
                $where[] = ['created_at', '<', date('Y-m-d', strtotime('+1 day'))];
                break;
            default:
                break;
        }
        return self::where($where)->count();
    }

    /**
     * @param int $senderId
     * @param int $receiverId
     * @return array|false
     */
    static function checkUnFetchedPushGift(int $senderId = 0, int $receiverId = 0)
    {
        if (!$senderId || !$receiverId) return false;
        $where = [
            ['user_id', $senderId],
            ['receive_user_id', $receiverId],
            ['flag', self::STATUS_WAIT],
            ['from','=',self::FROM_SYS_REGISTER_FEMALE]
        ];
        // if ($expTime = ConfigUtil::sysGiftExpireTime()) {
        //     $expDatetime = date('Y-m-d H:i:s', time() - $expTime);
        //     $where[] = ['created_at', '>=', $expDatetime];
        // }
        $items = self::where($where)->get()->toArray();
        $validItems = $expLogIds = [];
        foreach ($items as $item) {
            $validTime = time() - $item['exp_time'];
            //过期
            if ($item['exp_time'] > 0 && strtotime((string)$item['created_at']) < $validTime) {
                $expLogIds[] = $item['id'];
            } else {
                $validItems[] = $item;
            }
        }
        //过期状态修改
        $expLogIds && self::whereIn('id', $expLogIds)->update(['flag' => self::STATUS_EXP]);
        return $validItems;
    }
    /**
     * 查询所有未领取的礼物
     */
    static function checkUnFetched($senderId = 0, $receiverId = 0)
    {
        if (!$senderId || !$receiverId) return false;
        $where = [
            ['user_id', $senderId],
            ['receive_user_id', $receiverId],
            ['flag', self::STATUS_WAIT],
            ['from','<>',self::FROM_SYS_REGISTER_FEMALE]
        ];
        // if ($expTime = ConfigUtil::sysGiftExpireTime()) {
        //     $expDatetime = date('Y-m-d H:i:s', time() - $expTime);
        //     $where[] = ['created_at', '>=', $expDatetime];
        // }
        $items = self::where($where)->get()->toArray();
        $validItems = $expLogIds = [];
        foreach ($items as $item) {
            $validTime = time() - $item['exp_time'];
            //过期
            if ($item['exp_time'] > 0 && strtotime((string)$item['created_at']) < $validTime) {
                $expLogIds[] = $item['id'];
            } else {
                $validItems[] = $item;
            }
        }
        //过期状态修改
        $expLogIds && self::whereIn('id', $expLogIds)->update(['flag' => self::STATUS_EXP]);
        return $validItems;
    }

    static function expireRecordsPush($senderId = 0, $receiverId = 0){
        if (!$senderId || !$receiverId) return 0;

        $expDatetime = date('Y-m-d H:i:s', time() - FemaleKeepPushCode::GIFT_EXPIRATION_TIME);
        $where = [
            ['user_id', $senderId],
            ['receive_user_id', $receiverId],
            ['flag', self::STATUS_WAIT],
            ['created_at', '<', $expDatetime],
            ['from','=',self::FROM_SYS_REGISTER_FEMALE]
        ];
        return self::where($where)->update(['flag' => self::STATUS_EXP]);
    }
    /**
     * 失效记录修改
     */
    static function expireRecords($senderId = 0, $receiverId = 0, $hostSendMale = false)
    {
        if (!$senderId || !$receiverId) return 0;
        //过期时间
        $expTime = ConfigUtil::sysGiftExpireTime($hostSendMale);
        $expDatetime = date('Y-m-d H:i:s', time() - $expTime);
        $where = [
            ['user_id', $senderId],
            ['receive_user_id', $receiverId],
            ['flag', self::STATUS_WAIT],
            ['created_at', '<', $expDatetime],
            ['from','<>',GiftLog::FROM_SYS_REGISTER_FEMALE]
        ];
        return self::where($where)->update(['flag' => self::STATUS_EXP]);
    }

    /**
     * 系统礼物赠送总数
     */
    static function getSysCount($start = '', $end = '', $flag = -1, $type = 'count', $giftId = 0)
    {
        $where = [];
        if ($flag > -1) $where[] = ['flag', $flag];
        if ($start) $where[] = ['created_at', '>', $start];
        if ($end) $where[] = ['created_at', '<', $end];
        if (!$giftId) {
            $sysGiftIds = Gift::getSysGiftIds();
            $query = self::where($where)->whereIn('gift_id', $sysGiftIds);
        } else {
            $where[] = ['gift_id', $giftId];
            $query = self::where($where);
        }
        // dump($where);
        switch ($type) {
            case 'count':
                return $query->count();
            case 'send_user':
                $data = $query->select(Db::raw('count(distinct user_id) as ctn'))->first();
                return $data && $data->ctn ? $data->ctn : 0;
            case 'receive_user':
                $data = $query->select(Db::raw('count(distinct receive_user_id) as ctn'))->first();
                return $data && $data->ctn ? $data->ctn : 0;
            case 'coin':
                $data = $query->select(Db::raw('sum(gift_coin) as coin'))->first();
                return $data && $data->coin ? $data->coin : 0;
        }
        return 0;
    }

    /**
     * 收到礼物的信息
     */
    static function getReceivedGiftInfo($receiverId = 0)
    {
        if (!$receiverId) return false;
        $where = [
            ['receive_user_id', $receiverId],
            ['flag', self::STATUS_OK]
        ];
        $data = self::where($where)->select(['gift_id', Db::raw('sum(gift_num) as ctn')])->groupBy('gift_id')->get();
        $result = ['list' => [], 'total_num' => 0, 'total_coin' => 0];
        foreach ($data as $item) {
            if (!$item->giftInfo) continue;
            $giftCoin = intval($item->giftInfo->coin);
            $result['total_num'] += $item->ctn;
            $result['total_coin'] += $item->ctn * $giftCoin;
            $result['list'][] = [
                'gift_id' => $item->gift_id,
                'num' => $item->ctn,
                'name' => $item->giftInfo->name,
                'gift_coin' => $giftCoin,
                'icon' => AliyunUtil::IMG_HOST_V2 . $item->giftInfo->icon
            ];
        }
        array_multisort(array_column($result['list'], 'gift_coin'), SORT_DESC, $result['list']);
        return $result;
    }

    /**
     * 已赠送的记录
     */
    static function checkValidRecord($sender = 0, $from = 0, $type = 'count')
    {
        $where = [
            ['user_id', $sender],
            ['from', $from],
            ['flag', '<>', self::STATUS_EXP]
        ];
        return self::where($where)->count();
    }

    /**
     * 赠送礼物人数
     */
    static function checkSenderNum(
        $hostId = 0,
        $start = '',
        $end = '',
        $from = [self::FROM_SUPER_CHAT],
        $status = -1,
        $dataType = 'user'
    ) {
        $where = [['receive_user_id', $hostId]];
        $start && $where[] = ['created_at', '>', (string)$start];
        $end && $where[] = ['created_at', '<', (string)$end];
        $status > -1 && $where[] = ['flag', $status];
        if ($dataType == 'user') {
            $data = self::where($where)
                ->whereIn('from', $from)
                ->select(Db::raw('count(distinct user_id) as ctn'))->first();
            return $data && $data->ctn ? $data->ctn : 0;
        } else {
            return self::where($where)->whereIn('from', $from)->count();
        }
    }

    /**
     * 获取礼物排名
     */
    static function giftRankList($giftId = 0, $num = 10, $userId = 0, $start = '', $end = '')
    {
        if (!$giftId) return false;
        $where = [];
        if (is_array($giftId)) {
            $start && $where[] = ['gift_log.created_at', '>', $start];
            $end && $where[] = ['gift_log.created_at', '<', $end];

            $where[] = ['user_profile.role','=',2];

            $query = Db::table('gift_log')->join('user_profile','user_profile.user_id','=','gift_log.receive_user_id')->whereIn('gift_log.gift_id', $giftId)->where($where);
        } else {
            $where[] = ['gift_log.gift_id', $giftId];
            $start && $where[] = ['gift_log.created_at', '>', $start];
            $end && $where[] = ['gift_log.created_at', '<', $end];

            $where[] = ['user_profile.role','=',2];
            $query = Db::table('gift_log')->join('user_profile','user_profile.user_id','=','gift_log.receive_user_id')->where($where);
        }
        $data = $query->select(Db::raw('receive_user_id as user_id'), Db::raw('SUM(gift_num) as num'))->groupBy('receive_user_id')->orderBy('num', 'desc')->get()->toArray();

        $myRank = $myNum = 0;
        $res = [];
        foreach ($data as $k => $item) {
            $res[] = [
                'user_id' => $item->user_id,
                'num' => $item->num
            ];

            if ($item->user_id == $userId) {
                $myRank = $k + 1;
                $myNum = $item->num;
                break;
            }
        }

        return ['rank_list' => array_slice($res, 0, $num), 'my_rank' => $myRank, 'my_num' => $myNum];
    }

    /**
     * 查询记录
     */
    static function getSendLog(
        $senderId = 0,
        $receiverId = 0,
        $from = self::FROM_VIDEO_CALL_FREE,
        $offTime = ''
    ) {
        $where = [
            ['user_id', $senderId],
            ['receive_user_id', $receiverId],
            ['from', $from],
        ];
        $offTime && $where[] = ['created_at', '>', (string)$offTime];
        return self::where($where)->count();
    }

    /**
     * 上次正常送礼的记录
     */
    static function checkLastLog($senderId = 0, $minGiftCoin = 30)
    {
        $where = [
            ['user_id', $senderId],
            ['gift_coin', '>=', $minGiftCoin],
            ['flag', self::STATUS_OK]
        ];
        return self::where($where)->orderBy('id', 'desc')->first();
    }

    /**
     * 当前总送礼金币
     */
    static function checkTotalCost($userId = 0, $start = '')
    {
        $where = [
            ['user_id', $userId],
            ['flag', self::STATUS_OK]
        ];
        $start && $where[] = ['created_at', '>', (string)$start];
        $item = self::where($where)->select(Db::raw('SUM(gift_coin) as coin'))->first();
        return $item && $item->coin ? $item->coin : 0;
    }
}
